package aliyun

import (
	"fmt"
	"os"

	alidns20150109 "github.com/alibabacloud-go/alidns-20150109/v4/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

const Aliyun = "aliyun"

type Client struct {
	confList []aliyunDomainRecordRequest
}

func NewClient(confList []aliyunDomainRecordRequest) *Client {
	return &Client{confList: confList}
}

func (c *Client) Name() string {
	return Aliyun
}

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func (c *Client) createClient(accessKeyId *string, accessKeySecret *string) (_result *alidns20150109.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("alidns.cn-chengdu.aliyuncs.com")
	_result = &alidns20150109.Client{}
	_result, _err = alidns20150109.NewClient(config)
	return _result, _err
}

func (c *Client) update(conf *aliyunDomainRecordRequest) (resp *alidns20150109.UpdateDomainRecordResponse, err error) {
	// 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html
	client, err := c.createClient(
		tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")))
	if err != nil {
		return nil, err
	}

	updateDomainRecordRequest := &alidns20150109.UpdateDomainRecordRequest{
		Lang:         tea.String(""),
		UserClientIp: tea.String(""),
		RecordId:     conf.RecordId,
		RR:           conf.RR,
		Type:         conf.Type, // A 记录 固定
		TTL:          conf.TTL,
		Value:        &conf.Value, // 解析的ip
	}
	runtime := &util.RuntimeOptions{}
	resp, tryErr := func() (resp *alidns20150109.UpdateDomainRecordResponse, _e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		resp, err := client.UpdateDomainRecordWithOptions(updateDomainRecordRequest, runtime)
		if err != nil {
			return nil, err
		}

		return resp, nil
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 如有需要，请打印 error
		_, err = util.AssertAsString(error.Message)
		if err != nil {
			return nil, err
		}
	}
	return resp, err
}

//	Updated response:	{
//			"headers": {
//			   "access-control-allow-origin": "*",
//			   "access-control-expose-headers": "*",
//			   "connection": "keep-alive",
//			   "content-length": "84",
//			   "content-type": "application/json;charset=utf-8",
//			   "date": "Sun, 24 Dec 2023 08:39:18 GMT",
//			   "etag": "8uP+BRTINwRMByS5tZ9MP0Q4",
//			   "keep-alive": "timeout=25",
//			   "x-acs-request-id": "A2D7E12C-4F0E-5D8C-92B4-F0CBF3EA25DE",
//			   "x-acs-trace-id": "5215d2f19f992c22ec8a51050c0c2161"
//			},
//			"statusCode": 200,
//			"body": {
//			   "RecordId": "832424421522692096",
//			   "RequestId": "A2D7E12C-4F0E-5D8C-92B4-F0CBF3EA25DE"
//			}
//		 }
func (c *Client) Start(ip string) (bool, error) {
	for _, config := range c.confList {
		fmt.Printf("start update record: [%s], rr: [%s] to ip: [%s]. ttl: %d\n", *config.RecordId, *config.RR, ip, *config.TTL)
		config.Value = ip

		// 更新记录
		resp, err := c.update(&config)
		if err != nil {
			return false, err
		}

		fmt.Printf("Updated response: %v\n", resp)
		if resp == nil {
			fmt.Println("sync successful without update") // 域名解析ip没变
			return false, nil
		}

		if resp.StatusCode == nil {
			return false, fmt.Errorf("sync failed with status code: nil")
		}

		if *resp.StatusCode != 200 {
			return false, fmt.Errorf("sync failed with status code: %v", *resp.StatusCode)
		}
	}

	return true, nil
}
